<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录界面</title>
  <link rel="stylesheet" href="./css/style.css">
  <link rel="stylesheet" href="./css/body.css">
</head>

<body>
  <div class="container">
    <section id="content">
      <form>
        <h1>账号登录</h1>
        </h1>
        <div>
          <i class="close">X</i>
          <input type="text" placeholder="用户名" id="username" name="username">
        </div>
        <div>
          <i class="close">X</i>
          <input type="password" placeholder="密码" id="password" name="password">
        </div>
        <div>
          <input type="submit" value="登录" class="btn btn-primary" id="js-btn-login">
          <a href="../03-pwdBaseCode/index.html">忘记密码?</a>
          <a href="../02-regbaseCode/reg.html">注册账号</a>
        </div>
      </form>
    </section>
  </div>
  <script src="./lib/axios.js"></script>
  <script>
    // http://124.223.14.236:3001/api
    axios.defaults.baseURL = 'http://124.223.14.236:3001/api'

    // 封装获取元素
    const qs = ele => document.querySelector(ele)

    // 表单提交事件
    qs('form').addEventListener('submit', async function (e) {
      e.preventDefault()
      if (qs('#username').value.trim().length <= 0 || qs('#password').value.trim().length <= 0) {
        return alert("输入不能为空")
      }

      let data = {
        username: qs('#username').value,
        password: qs('#password').value,
      }
      await axios({
        method: 'POST',
        url: '/user/login',
        data,
      }).then(({ data }) => {
        if (data.success) {
          localStorage.setItem('token', JSON.stringify(data.data.token));
          alert('登录成功')
          location.href = '../04-goodBaseCode/index.html'
          qs("form").reset()
        } else {
          return alert("用户名或密码不正确")
        }
      })
    })
  </script>
</body>

</html>